<template>
  <div class="app-container">
    <el-row class="mb-4">
      <el-button
        type="success"
        icon="CirclePlus"
        plain
        @click="handleAddHatList()"
        v-hasPermi="['core:hat:add']"
        >新增
      </el-button>
      <el-button
        type="primary"
        icon="Edit"
        plain
        :disabled="single"
        @click="handleEdit"
        v-hasPermi="['core:hat:edit']"
        >编辑
      </el-button>
      <el-button
        type="danger"
        icon="Delete"
        plain
        :disabled="multiple"
        @click="handleDeleteHatList"
        v-hasPermi="['core:hat:remove']"
        >删除
      </el-button>
      <el-button
        type="warning"
        icon="Delete"
        plain
        @click="handleHatExport"
        v-hasPermi="['core:hat:export']"
        >导出
      </el-button>
    </el-row>
  </div>
  <div class="table-tools mb8">
    <el-table
      :data="hatList"
      ref="hatList"
      v-loading="recordLoading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" />
      <el-table-column align="center" type="index" label="序号" width="70" />
      <el-table-column align="center" prop="hat.imei" label="编号" />
      <el-table-column align="center" prop="hat.name" label="安全帽名称" />
      <el-table-column
        align="center"
        prop="sysUser.nickName"
        label="使用者姓名"
      />
      <el-table-column
        align="center"
        prop="sysUser.dept.deptName"
        label="所属部门"
      />
      <el-table-column align="center" prop="hat.deviceStatus" label="当前状态">
        <template #default="scope">
          <el-tag
            :type="scope.row.hat?.deviceStatus === 1 ? 'success' : 'danger'"
            >{{ scope.row.hat?.deviceStatus === 1 ? "在线" : "离线" }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="hat.battery"
        label="电量"
        :formatter="batteryFormatter"
      />
      <el-table-column align="center" label="查看位置">
        <template #default="{ row }">
          <el-button
            type="primary"
            text
            bg
            icon="MapLocation"
            @click="openLocationDialog(row)"
            >查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="operation" label="操作" width="250">
        <template #default="scope">
          <el-button
            type="success"
            plain
            @click="infoHat(scope.row)"
            v-hasPermi="['core:hat:query']"
            >详情
          </el-button>
          <el-button
            type="primary"
            plain
            @click="handleRowEdit(scope.row)"
            v-hasPermi="['core:hat:edit']"
            >编辑
          </el-button>
          <el-button
            type="danger"
            plain
            @click="handleDeleteHat(scope.row)"
            v-hasPermi="['core:hat:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <pagination
    :total="recordTotal"
    v-model:page="queryForm.pageNum"
    v-model:limit="queryForm.pageSize"
    @pagination="getHatList"
  />

  <el-dialog
    title="安全帽位置"
    width="65%"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    :before-close="beforeCloseLocationDialog"
    append-to-body
    destroy-on-close
    v-model="locationDialogVisible"
  >
    <div class="map-container" ref="mapContainer"></div>
  </el-dialog>
  <el-dialog
    :title="试题管理"
    v-model="dialogHatInfo"
    class="aboutDialog"
    width="1000px"
    :before-close="beforeCloseLocationDialog"
  >
    <el-form :modle="ruleForm" class="demo-infoForm">
      <el-col :span="26" class="card-box">
        <el-card>
          <template #header><span>安全帽基本信息</span> </template>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <table cellspacing="0" style="width: 100%">
              <tbody>
                <tr>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">名称:</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="ruleForm.name">
                      {{ ruleForm.name }}
                    </div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">IMEI:</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="ruleForm.imei">
                      {{ ruleForm.imei }}
                    </div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">上线时间:</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div
                      class="cell"
                      width="170px"
                      v-if="ruleForm.recentOnlineDate"
                    >
                      {{ ruleForm.recentOnlineDate }}
                    </div>
                  </td>
                </tr>
                <tr>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">使用者姓名:</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="ruleForm.nickName">
                      {{ ruleForm.nickName }}
                    </div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">部门:</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="ruleForm.deptName">
                      {{ ruleForm.deptName }}
                    </div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">工号:</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="ruleForm.userName">
                      {{ ruleForm.userName }}
                    </div>
                  </td>
                </tr>
                <tr>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">注册时间:</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="ruleForm.createTime">
                      {{ ruleForm.createTime }}
                    </div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">状态:</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="ruleForm.deviceStatus">
                      {{ ruleForm.deviceStatus === 1 ? "在线" : "离线" }}
                    </div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">电量:</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="ruleForm.battery">
                      {{ ruleForm.battery + "%" }}
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </el-card>
      </el-col>
    </el-form>
    <div class="info">
      <el-date-picker
        v-model="dateChooseValue"
        type="datetimerange"
        :picker-options="pickerOptions"
        range-separator="至"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        value-format="YYYY-MM-DD HH:mm:ss"
      >
      </el-date-picker>

      <el-button type="primary" @click="submitDateChoose">确 定</el-button>
      <el-button @click="cancelDateChoose">取 消</el-button>
    </div>
    <div class="map-container" ref="mapContainer" style="height: 350px" />
  </el-dialog>
  <el-dialog
    v-model="dialogFormVisible"
    :title="stateTitle ? '添加安全帽' : '修改安全帽'"
    :before-close="handleClose"
    width="60%"
  >
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleFormRef"
      class="demo-ruleForm"
    >
      <el-form-item label="IMEI号:" prop="imei">
        <el-input
          v-model="ruleForm.imei"
          maxlength="15"
          show-word-limit
          style="width: 300px"
        ></el-input>
      </el-form-item>
      <el-form-item label="安全帽名称:" prop="name">
        <el-input
          v-model="ruleForm.name"
          placeholder="给目标取个名字"
          style="width: 283px"
        ></el-input>
      </el-form-item>
      <el-form-item label="使用工号:" prop="userId">
        <user-select v-model="ruleForm.userId" placeholder="编号" />
      </el-form-item>
      <el-form-item v-show="false" label="" prop="createTime">
        <el-input v-model="ruleForm.createTime"></el-input>
      </el-form-item>

      <!--      <el-form-item label="部门:" prop="deptName">
        <el-select v-model="ruleForm.dept" placeholder="请选择活部门">
          <el-option label="质量科" value="质量科"></el-option>
          <el-option label="生产科" value="生产科"></el-option>
          <el-option label="装备科" value="装备科"></el-option>
        </el-select>
      </el-form-item>-->
    </el-form>
    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import {
  getHatList,
  addHat,
  getHat,
  deleteHat,
  updateHat,
  getHistoryTrace,
} from "@/api/core/hat";
import { key, keyCode } from "@/constant/amap";
import AMapLoader from "@amap/amap-jsapi-loader";
import helmetPointImageUrl from "@/assets/images/helmet_point.png";
import { markRaw } from "vue";
import { mapState } from "pinia";
import useCallStore from "@/store/modules/call";
import { deviceType } from "@/constant/deviceType";
export default {
  setup() {},
  data() {
    return {
      queryForm: {
        pageNum: 1,
        pageSize: 10,
      },
      stateTitle: true,
      recordLoading: false,
      single: true,
      multiple: true,
      hatList: [],
      Ids: [],
      currentHatId: undefined,
      hatTableMultiple: true,
      recordTotal: 0,
      locationDialogVisible: false,
      dialogFormVisible: false,
      dialogHatInfo: false,
      infoForm: {},
      recordIds: [],
      ruleForm: {},
      deviceType,
      helmetMarkerMap: markRaw({}),
      markerLayers: null,
      map: null,
      // 选择时间对话框
      dateChooseTitle: "",
      dateChooseOpen: false,
      // 选择的日期范围
      dateChooseValue: "",
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
        disabledDate(date) {
          // disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
          return date.getTime() >= Date.now();
        },
      },

      rules: {
        imei: [
          {
            required: true,
            message: "IMEI号位于安全帽内部后侧，靠近电池仓位",
            trigger: "blur",
          },
          {
            pattern: /\d{15}/,
            message: "IMEI长度固定为15位纯数字",
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    ...mapState(useCallStore, {
      helmetList(store) {
        const rtcDeviceMap = store.rtcDeviceMap;
        const helmetList = [];
        for (const key in rtcDeviceMap) {
          const deviceList = rtcDeviceMap[key];
          for (const device of deviceList) {
            if (device.deviceType === this.deviceType.Helmet.value) {
              helmetList.push(device);
              break;
            }
          }
        }
        return helmetList;
      },
    }),
  },
  // watch: {
  //   helmetList() {
  //     this.loadLabelMarker()
  //   }
  // },
  created() {
    console.log("created-helmetList", this.helmetList);
    this.getHatList();
  },

  mounted() {
    //  this.loadMapAndLocation()
  },

  methods: {
    // 提交选择的轨迹时间范围
    submitDateChoose() {
      this.dateChooseOpen = false;
      this.drawTracks(this.dateChooseValue); //显示轨迹
    },
    cancelDateChoose() {
      this.dateChooseOpen = false;
    },
    drawTracks(timeArr) {
      let params = {
        hatId: this.currentHatId,
        startTime: timeArr[0],
        endTime: timeArr[1],
      };
      getHistoryTrace(params).then((res) => {
        if (res.data.length !== 0) {
          let path = [];
          for (let i = 0; i < res.data.length; i++) {
            let data = res.data[i];
            path.push([data.longitude, data.latitude]);
          }
          let polyline = new AMap.Polyline({
            path,
            showDir: true,
            strokeColor: "#3366FF",
            strokeWeight: 3,
            strokeStyle: "solid",
            lineJoin: "round",
            lineCap: "round",
            dirColor: "white",
          });
          polyline.on("rightClick", () => {
            this.map.remove(polyline);
          });
          this.map.add(polyline);
          // 缩放地图到合适的视野级别
          this.map.setFitView([polyline]);
        } else {
          this.$modal.msgError("该帽子没有历史轨迹！");
        }
      });
    },

    batteryFormatter(row) {
      return row.hat.battery !== null ? row.hat.battery + "%" : "";
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    resetQueryForm() {
      this.queryForm = {
        pageNum: 1,
        pageSize: 10,
      };
      this.getHatList();
    },
    async loadMapAndLocation(row) {
      if (!window.AMap) {
        window._AMapSecurityConfig = {
          securityJsCode: keyCode,
        };
        try {
          await AMapLoader.load({
            key,
            version: "2.0",
            plugins: [
              "AMap.MouseTool",
              "AMap.ContextMenu",
              "AMap.PolyEditor",
              "AMap.MapType",
              "AMap.Scale",
              "AMap.OverView",
              "AMap.ControlBar",
              "Map3D",
              "AMap.DistrictSearch",
              "AMap.MarkerClusterer",
              "AMap.ToolBar",
              "AMap.Geolocation",
            ],
          });
        } catch (e) {
          this.$modal.msgError("地图加载失败");
        }
      }

      this.map = markRaw(
        new AMap.Map(this.$refs.mapContainer, {
          //设置地图容器id
          resizeEnable: true,
          rotateEnable: true,
          pitchEnable: true,
          showLabel: true, //是否显示地图文字标记
          zoom: 18,
          zooms: [3, 20],
          rotation: -15,
          viewMode: "3D", //开启3D视图,默认为关闭
          skyColor: "#132237",
          cursor: "hand", // 鼠标在地图上的表现形式
          expandZoomRange: true,
        })
      );
      const geoLocation = new AMap.Geolocation({
        enableHighAccuracy: true,
        timeout: 5000,
        maximumAge: 0,
        convert: true,
        showButton: true,
        position: "RB",
        offset: [20, 90],
        showMarker: true,
        showCircle: true,
        panToLocation: true,
        zoomToAccuracy: true,
      });
      this.map.addControl(geoLocation);
      geoLocation.getCurrentPosition(() => {});
      this.map.addControl(new AMap.ToolBar());
      this.map.addControl(new AMap.ControlBar());
      this.map.addControl(new AMap.Scale());
      this.map.addControl(new AMap.MapType({ defaultType: 1 }));

      this.markerLayers = markRaw(
        new AMap.LabelsLayer({
          collision: true,
        })
      );
      this.map.add(this.markerLayers);

      this.loadLabelMarker(row);
    },

    loadLabelMarker(row) {
      //console.log('map',this.map);
      if (this.map === null) {
        return;
      }
      const deviceList = this.helmetList;
      //console.log('helmetList', this.helmetList)
      for (const device of deviceList) {
        if (row.hat.userId === device.userId) {
          const { userId, nickName, latitude, longitude } = device;

          if (latitude === null || longitude === null) {
            continue;
          }
          const labelMarker = this.helmetMarkerMap[userId];
          console.log("helmetMarkerMap1", this.helmetMarkerMap);
          if (labelMarker) {
            console.log("longitude, latitude", longitude, latitude);
          } else {
            const marker = new AMap.LabelMarker({
              position: [longitude, latitude],
              icon: {
                image: helmetPointImageUrl,
                // offset: [-12, -12]
              },
              text: {
                content: nickName,
                offset: [0, 40],
                style: {
                  backgroundColor: "#eee",
                  borderColor: "#333",
                  borderWidth: 1,
                },
              },
            });

            this.helmetMarkerMap[userId] = marker;
            console.log("helmetMarkerMap2", this.helmetMarkerMap);
            this.markerLayers.add(marker);
            this.map.panTo([longitude, latitude]);
          }
        }
      }
    },

    openLocationDialog(row) {
      this.locationDialogVisible = true;
      this.$nextTick(() => {
        this.loadMapAndLocation(row);
      });
    },
    beforeCloseLocationDialog(done) {
      if (this.map) {
        this.map.destroy();
        this.map = null;
        this.helmetMarkerMap = markRaw({});
      }
      done();
    },
    getHatList() {
      this.recordLoading = true;
      getHatList(this.queryForm)
        .then((res) => {
          const { rows, total } = res;
          this.hatList = rows;
          this.recordTotal = total;
        })
        .finally(() => {
          this.recordLoading = false;
        });
    },
    infoHat(row) {
      this.currentHatId = row.hat.id;
      const Ids = row.hat.id;
      const id = JSON.parse(JSON.stringify(Ids));
      getHat(id).then((res) => {
        this.ruleForm = {
          imei: res.data.hat.imei,
          name: res.data.hat.name,
          userId: res.data.sysUser.userId,
          //deptName: res.data.sysUser.dept.deptName || undefined
          //deptName:(res.data.sysUser.dept.deptName === undefined) ? undefined:res.data.sysUser.dept.deptName
          deptName: res.data.sysUser?.dept?.deptName,
          createTime: res.data.sysUser.createTime,
          deviceStatus: res.data.hat.deviceStatus,
          userName: res.data.sysUser.userName,
          nickName: res.data.sysUser.nickName,
          recentOnlineDate: res.data.hat.recentOnlineDate,
          battery: res.data.hat.battery,
        };
      });
      console.log(this.ruleForm);
      this.dialogHatInfo = true;
      this.$nextTick(() => {
        this.loadMapAndLocation(row);
      });
    },
    handleAddHatList() {
      this.reset();
      this.stateTitle = true;
      this.dialogFormVisible = true;
    },
    cancel() {
      this.reset();
      this.dialogFormVisible = false;
    },
    submitForm() {
      this.$refs.ruleFormRef.validate((valid) => {
        if (valid) {
          if (this.stateTitle === false) {
            updateHat(this.ruleForm).then((res) => {
              this.$modal.msgSuccess("修改成功");
              this.dialogFormVisible = false;
              this.getHatList();
            });
          } else {
            addHat(this.ruleForm).then((res) => {
              this.$modal.msgSuccess("添加成功");
              this.dialogFormVisible = false;
              this.getHatList();
            });
          }
        }
      });
    },
    reset() {
      this.resetForm("ruleFormRef");
      this.ruleForm = {};
      if (this.$refs.ruleFormRef) {
        this.$refs.ruleFormRef.clearValidate();
      }
    },
    handleSelectionChange(selection) {
      console.log(selection);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    //安全帽删除
    async handleDeleteHat(row) {
      const recordIds = row.hat.id;
      await this.$modal
        .confirm("是否确认删除数据?")
        .then(function () {
          return deleteHat(recordIds);
        })
        .then(() => {
          this.getHatList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /*async deleteHat(recordIds) {
      await deleteHat(recordIds)
      this.getHatList()
      this.$modal.msgSuccess('删除成功')
    },*/
    /* async handleDeleteHat(row) {
      await this.$modal.confirm('您确定要删除此条数据吗？')
      const recordIds = [row.hat.id]
      await this.deleteHat(recordIds)
    },*/
    async handleDeleteHatList() {
      const rows = this.$refs.hatList.getSelectionRows();
      console.log("121222", rows);
      const recordIds = rows.map((item) => item.hat.id);
      await this.$modal
        .confirm("您确定要删除勾选的数据吗？")
        .then(function () {
          console.log(recordIds);
          return deleteHat(recordIds);
        })
        .then(() => {
          this.getHatList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    //安全帽修改
    handleRowEdit(row) {
      this.stateTitle = false;
      const Ids = row.hat.id;
      const id = JSON.parse(JSON.stringify(Ids));
      getHat(id).then((res) => {
        this.ruleForm = {
          imei: res.data.hat.imei,
          name: res.data.hat.name,
          userId: res.data.sysUser.userId,
          id: res.data.hat.id,
        };
        console.log(this.ruleForm);
        this.dialogFormVisible = true;
      });
    },
    handleEdit() {
      this.stateTitle = false;
      const rows = this.$refs.hatList.getSelectionRows();
      console.log("223", rows);
      const id = { ...rows.map((item) => item.hat.id) };
      console.log("112211", id);
      getHat(id[0]).then((res) => {
        this.ruleForm = {
          imei: res.data.hat.imei,
          name: res.data.hat.name,
          userId: res.data.sysUser.userId,
          id: res.data.hat.id,
        };
        console.log(this.ruleForm);
        this.dialogFormVisible = true;
      });
    },
    //导出安全帽信息
    handleHatExport() {
      this.download(
        `/core/hat/export`,
        {
          ...this.queryParams,
        },
        `core_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.el-table .el-table__cell {
  padding: 0;
}
.map-container {
  height: 500px;
  padding-top: 10px;
}
.app-container {
  padding: 15px;
}
.info {
  display: inline-flex;
  align-items: center;
  max-width: max-content;
  margin-right: inherit;
  margin-left: 15px;
  padding-bottom: 10px;
}

::v-deep .el-range-editor--small.el-input__wrapper {
  margin-right: 30px;
}
::v-deep .el-dialog__header {
  padding: 0;
}
::v-deep .el-card__body {
  padding: 0px 10px 10px 10px !important;
}
</style>
